package com.example.myletcodelearing.chaintable

/**
 * @author tgw
 * @date 2022/8/1
 * @describe 双向链表
 */
class DulNode {

    var value = -1
    var pre: DulNode? = null
    var next: DulNode? = null
    override fun toString(): String {
        return "DulNode(value=$value, pre=$pre, next=$next)"
    }


}

fun main(array: Array<String>) {
    println("测试开始双向链表")
    val test = TestDulChainNode()

    test.insertNode(0,1)
    test.insertNode(0,2)
    test.insertNode(2,3)
    test. printNode()
//    println("${test.head0.toString()}")
    println("测试删除双向链表")
    test.deleted(2)
    test.printNode()
}

class TestDulChainNode {

    var head0:DulNode? = DulNode().apply {
        value = -1
    }

    var size = 0

    fun insertNode(index: Int, value: Int) {
        if (index>size){
            println("越界$index")
            return
        }
        var i =0
        var p :DulNode?=head0
        while (i!=index){
            p = p?.next
            i++
        }
        var insertNode :DulNode? = DulNode().apply {
            this.value = value
        }
        var insertNode1 :DulNode? = DulNode().apply {
            this.value = value
        }
        var p1 :DulNode? = DulNode().apply {
            this.value = p?.value?:0
        }
        insertNode?.pre =p1
        insertNode?.next =p?.next

        p?.next?.pre =insertNode1

        p?.next=insertNode

//        insertNode?.next = head0?.next;
//        head0?.next = insertNode;
//        insertNode?.pre = head0;
//        insertNode?.next?.pre = insertNode;

        size++
    }

    fun deleted(index: Int) {
        if (index>=size){
            println("删除越界$index")
            return
        }
        var i =0
        var p :DulNode?=head0
        while (i!=index){
            p = p?.next
            i++
        }
        p?.next?.next?.pre = p?.next?.pre
        p?.next = p?.next?.next
        size--
    }

    fun printNode() {
        var p :DulNode?=head0
        while (p!=null){
            println("${p.toString()}")
            p = p.next
        }

    }
}